<template>
	<el-dialog :visible.sync="visible" width="1200px" :title="!dataForm.id ? '新增' : '编辑'" @close="close" :close-on-click-modal="false" :close-on-press-escape="false">
		<div class="cpbcourse">
			<el-steps :active="step.active">
				<el-step title="第一步" description="基本信息" />
				<el-step title="第二步" description="内容编辑" />
			</el-steps>
			<br />
			<template v-if="step.active == 1">
				<el-form ref="dataForm" :model="dataForm" :rules="formRule" label-width="120px">
					<el-form-item prop="classifyId" label="课程分类:" v-if="dataForm.id">
						<el-select v-model="dataForm.classifyId" clearable placeholder="请选择">
							<el-option :label="selLeftTree.name" :value="selLeftTree.id">
								<el-tree
									:data="leftTreeData"
									:props="{
										children: 'children',
										label: 'name',
									}"
									accordion
									highlight-current
									@node-click="handleSelectionChange"
								></el-tree>
							</el-option>
						</el-select>
					</el-form-item>
					<el-form-item prop="courseName" label="课程名称:">
						<el-input v-model="dataForm.courseName" placeholder="请输入课程名称" maxlength="64" show-word-limit></el-input>
					</el-form-item>
					<el-form-item label="课程简介:" prop="courseSynopsis">
						<el-input type="textarea" row="3" maxlength="200" v-model="dataForm.courseSynopsis" placeholder="请输入课程简介" show-word-limit></el-input>
					</el-form-item>
					<el-form-item prop="coverImg" label="封面图片:">
						<!-- <fortress-upload type="image" name="coverImg" :formData="dataForm"></fortress-upload> -->
						<picture-upload type="picture-card" v-model="dataForm.coverImg" :autoCropWidth="182" :autoCropHeight="132" :fixed="false" :fixedBox="true" :limit="1" :mode="'182px 132px'" :centerBox="false" tip="，图片大小为182 x 132"></picture-upload>
					</el-form-item>
					<el-form-item label="是否首页推荐: " prop="isRecommend">
						<el-radio-group v-model="dataForm.isRecommend">
							<el-radio :label="2">否</el-radio>
							<el-radio :label="1">是</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="排序" :label-width="formLabelWidth" prop="sort">
						<template #label>
							<span style="margin-right: 7px;">排序</span>
							<el-tooltip class="item" effect="dark" content="数字越大越靠前" placement="top">
								<i class="el-icon-info"></i>
							</el-tooltip>
						</template>
						<el-input-number v-model="dataForm.sort"></el-input-number>
					</el-form-item>
				</el-form>
			</template>
			<template v-else>
				<el-row class="warp">
					<el-col class="left" :span="6">
						<div class="header">
							<span>章节</span>
							<em>可拖动排序</em>
						</div>
						<draggable class="draggable" v-model="chapters.list" :options="{ animation: 140 }">
							<transition-group tag="ul">
								<li v-for="item in chapters.list" :key="item.index" :class="{ active: chapters.row.index == item.index }" @click="activeChapters(item)">
									<div>
										<template v-if="chapters.titleEdit != item.index">{{ item.chapterName }}</template>
										<el-input clear="chapters-title-input" v-else type="text" size="mini" v-model="chapters.chapterName" maxlength="20" show-word-limit />
									</div>
									<span class="btn">
										<template v-if="chapters.titleEdit != item.index">
											<el-button icon="el-icon-edit" style="margin-right: 10px;" type="text" @click="toEditTitle(item)"></el-button>
											<el-popconfirm placement="top" title="确定要删除此章节吗？" v-if="chapters.list.length > 1" @confirm="deleteChapters(item)">
												<el-button slot="reference" icon="el-icon-delete" type="text"></el-button>
											</el-popconfirm>
										</template>
										<template v-else>
											<el-button style="margin-right: 10px;" icon="el-icon-circle-check" type="text" @click="saveTitleEditing"></el-button>
											<el-popconfirm placement="top" title="确定要取消编辑此章节吗？" @confirm="cancelTitleEditing">
												<el-button slot="reference" icon="el-icon-circle-close" type="text"></el-button>
											</el-popconfirm>
										</template>
									</span>
								</li>
							</transition-group>
						</draggable>
						<div class="footer" @click="addChapters">+ 添加章节</div>
					</el-col>

					<el-col class="right" :span="18">
						<div class="header">
							<span>{{ chapters.row.chapterName }}</span>
							<el-button type="warning" size="small" class="title-btn" @click="openChaptersDialog">添加课件</el-button>
						</div>
						<div class="table">
							<div class="thead">
								<div class="th number">序号</div>
								<div class="th name">课件名</div>
								<div class="th">类型</div>
								<div class="th">操作</div>
							</div>
							<draggable class="tbody" :options="{ animation: 140 }" v-model="chapters.row.coursewares" @change="change">
								<transition-group tag="ul">
									<li v-for="(item, index) in chapters.row.coursewares" :key="item.id">
										<div class="th number">{{ index + 1 }}</div>
										<div class="th name">{{ item.coursewareName }}</div>
										<div class="th">
											<!-- {{ $getDictLabel("courseware_type", item.coursewareType) }} -->
											{{ coursewareTypeFmt(item) }}
										</div>
										<div class="th">
											<el-button type="text" style="color: #f56c6c" @click="deleteCourseware(item)">删除</el-button>
										</div>
									</li>
								</transition-group>
							</draggable>
						</div>
					</el-col>
				</el-row>
			</template>
		</div>
		<template #footer>
			<el-button v-if="step.active == 2" type="default" @click="toPrev">上一步</el-button>
			<el-button v-if="step.active == 2" type="warning" @click="saveCourseDraft" :loading="saveloading">保存草稿</el-button>
			<el-button v-if="step.active == 2" type="success" @click="saveCourse" :loading="saveloading">发布</el-button>
			<el-button type="error" @click="cancel">取消</el-button>
			<el-button v-if="step.active == 1" type="success" @click="saveAndNext">保存并继续</el-button>
		</template>

		<vSelectCourseware :leftTreeData="leftTreeData" ref="vSelectCoursewareRef"></vSelectCourseware>
	</el-dialog>
</template>

<script>
import { studycourseInfo, studycourseSave, studycourseEdit, editCourseStatus } from "@/api/study/course/studycourse.js"
import { enumList } from "@/api/public.api.js"
import { detailByCourseId, saveStudyCourseChapter } from "@/api/study/course/studycoursechapter.js"
import debounce from "lodash/debounce"
import draggable from "vuedraggable"
import { dictList } from "@/api/public.api.js"
import vSelectCourseware from "./components/select-courseware.vue"
import pictureUpload from "@/components/fortress-upload/picture-upload.vue"

export default {
	name: "studycourseEdit",
	props: ["leftTreeData"],
	data() {
		return {
			selLeftTree: {},
			searchSelLeftTree: {},
			formLabelWidth: "120px",
			saveloading: false,
			firstCourseId: "", //课程的ID  第一步的ID
			visible: false,
			dataForm: {
				id: "",
				classifyId: "",
				is_recommend: "",
				courseName: "",
				coverImg: "",
				courseSynopsis: "",
				courseStatus: "",
				classStatus: "",
				sort: 1,
				creator: "",
				createDate: "",
				updater: "",
				updateDate: "",
				isDelete: "",
				cpbAuthorityDTO: {},
			},
			formRule: {
				classifyId: [{ required: true, message: "请选择课程分类", trigger: "change" }],
				courseName: [{ required: true, message: "请输入课程名称", trigger: "change" }],
				coverImg: [{ required: true, message: "请上传封面图片", trigger: "change" }],
			},
			gridPage: {
				current: 1,
				total: 0,
				size: 10,
			},
			step: {
				active: 1,
			},
			chapters: {
				list: [
					{
						chapterName: "第一章",
						courseId: "",
						index: 0,
						coursewares: [],
					},
				],
				row: {
					coursewares: [],
				},
				chapterName: "",
				titleEdit: -1,
			}, // 章节列表
			checkList: [],
			visiblePermissionsVisible: false, //可见范围弹窗状态
			CoursewareTypeList: [],
			yesNoList: [],
		}
	},
	created() {},
	computed: {
		dataRule() {
			return {
				// examName: [{ required: true, message: "请输入考试名称", trigger: "change" }],
				// examTime: [{ required: true, message: "请输入答题时长", trigger: "change" }],
				cpbAuthorityDTO: [
					{
						required: true,
						message: "请输入考试对象",
						trigger: "change",
						validator(r, v, c) {
							if (Object.values(v).join("") == "") {
								return c(new Error("请输入考试对象"))
							}
							return c()
						},
					},
				],
			}
		},
		visiblePermissions: {
			get() {
				if (!this.dataForm.cpbAuthorityDTO) {
					this.dataForm.cpbAuthorityDTO = {}
				}
				const list = []
				if (this.dataForm.cpbAuthorityDTO.deptName) {
					list.push(this.dataForm.cpbAuthorityDTO.deptName)
				}
				if (this.dataForm.cpbAuthorityDTO.memberName) {
					list.push(this.dataForm.cpbAuthorityDTO.memberName)
				}
				if (this.dataForm.cpbAuthorityDTO.tagName) {
					list.push(this.dataForm.cpbAuthorityDTO.tagName)
				}
				return list.join(" | ")
			},
			set(value) {
				this.dataForm.cpbAuthorityDTO = {
					...this.dataForm.cpbAuthorityDTO,
					...value,
				}
			},
		},
	},
	methods: {
		queryDictList() {
			this.yesNoList = []
			dictList("yesNo").then(resp => {
				if (resp.code == 0) {
					this.feedbackList = resp.data
				}
			})
		},
		change(e) {
			console.log(e)
		},
		//可见范围
		showVisiblePermissions() {
			this.visiblePermissionsVisible = true
		}, //保存
		saveVisiblePermissions(data) {
			const { dept, psls, tags, deptName, pslsName, tagsName } = data

			this.visiblePermissions = {
				deptId: dept.join(","),
				memberId: psls.join(","),
				tag: tags.join(","),
				deptName: deptName.join(","),
				memberName: pslsName.join(","),
				tagName: tagsName.join(","),
			}
		},
		openChaptersDialog() {
			// this.checkList = []
			this.$refs["vSelectCoursewareRef"].show([].concat(this.chapters.row.coursewares), checked => {
				this.chapters.row.coursewares = checked
			})
		},
		close() {
			this.saveloading = false
			this.firstCourseId = ""
			this.dataForm = {
				id: "",
				classifyId: "",
				courseName: "",
				coverImg: "",
				courseSynopsis: "",
				courseStatus: "",
				classStatus: "",
				tenantCode: "",
				creator: "",
				createDate: "",
				updater: "",
				updateDate: "",
				isDelete: "",
				cpbAuthorityDTO: {},
				sort: 0,
				isRecommend: 2,
			}

			this.gridPage = {
				current: 1,
				total: 0,
				size: 10,
			}
			this.step = {
				active: 1,
			}
			this.chapters = {
				list: [
					{
						chapterName: "章节1",
						courseId: "",
						index: 0,
						coursewares: [],
					},
				],
				row: {
					coursewares: [],
				},
				chapterName: "",
				titleEdit: -1,
			} // 章节列表
			this.checkList = []
			this.$emit("refreshData")
			this.visible = false
			this.CoursewareTypeList = []
		},
		// 上一步
		toPrev() {
			this.step.active = 1
		},
		// 章节点击展示
		activeChapters(item) {
			console.log(item, "item")
			if (item.coursewares.length == 0) {
				// this.checkList = []
			}
			this.chapters.row = item
		},
		// 查询正在编辑名称的章节下标
		nowEditChapters(index = this.chapters.titleEdit) {
			return this.chapters.list.findIndex(item => item.index == index)
		},
		// 开始编辑章节名称
		toEditTitle(item) {
			if (this.chapters.titleEdit != -1) {
				return
			}
			this.chapters.titleEdit = item.index
			this.chapters.chapterName = item.chapterName
		},
		// 保存章节名称编辑
		saveTitleEditing() {
			// todo 提交修改信息
			if (this.chapters.chapterName == "") {
				return this.$message.error("章节名不能为空！")
			}
			this.chapters.list[this.nowEditChapters()].chapterName = this.chapters.chapterName
			this.chapters.titleEdit = -1
			this.chapters.chapterName = ""
		},
		// 取消章节名称编辑
		cancelTitleEditing() {
			if (this.chapters.list[this.nowEditChapters()].chapterName == "") {
				this.deleteChapters()
			}
			this.chapters.titleEdit = -1
			this.chapters.chapterName = ""
		},
		// 删除一条章节
		deleteChapters(item = this.chapters.list[this.nowEditChapters()]) {
			// todo 删除章节 item
			this.chapters.list.splice(this.nowEditChapters(item.index), 1)
			this.chapters.row = this.chapters.list[0] || {}
		},
		// 添加一条章节
		addChapters() {
			if (this.chapters.titleEdit != -1) {
				return
			}
			const index = this.$tools.uid(5)
			this.chapters.list.push({
				index,
				chapterName: "",
				coursewares: [],
			})
			this.chapters.row.index = this.chapters.list.length
			this.chapters.titleEdit = index
			this.chapters.chapterName = ""
		},
		// 删除课件
		deleteCourseware(item) {
			this.$confirm("删除后不可恢复，您确定要删除吗？", "删除确认", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
			}).then(() => {
				this.chapters.row.coursewares.splice(this.findCourseware(item), 1)
				this.$message({
					type: "success",
					message: "删除成功!",
				})
			})
		}, // 查找课件
		findCourseware(item) {
			return this.chapters.row.coursewares.findIndex(e => e.id == item.id)
		},
		// 初始化
		init(id, treeId) {
			this.visible = true
			this.step.active = 1
			this.$nextTick(() => {
				if (treeId) {
					this.classifyId = treeId
					this.dataForm.classifyId = treeId
				}
				this.queryEnumList()

				if (id) {
					this.dataForm.id = id
					this.getInfo()
					this.step.active = 2
				}
			})
		},
		// 获取信息
		getInfo() {
			studycourseInfo(this.dataForm.id).then(resp => {
				if (resp.code == 0) {
					this.$nextTick(() => {
						this.dataForm = {
							...this.dataForm,
							...resp.data,
						}
						this.selLeftTree = {
							id: resp.data.classifyId,
							name: resp.data.classifyIdName,
						}
						this.firstCourseId = resp.data.id
						this.saveAndNext(null)
					})
				} else {
					this.$msg({
						message: resp.msg,
						type: "error",
					})
				}
			})
		},
		saveAndNext(flag) {
			//第一步保存
			if (this.dataForm.id) {
				this.getNextInfo()
			}
			this.dataForm.coverImg = typeof this.dataForm.coverImg == "string" ? this.dataForm.coverImg : this.dataForm.coverImg[0].path
			if (flag) {
				this.dataFormSubmitHandle()
			}
		},
		getNextInfo() {
			detailByCourseId(this.dataForm.id).then(resp => {
				if (resp.code == 0) {
					console.log(resp.data, "data")

					if (resp.data.length != 0 && resp.data[0].coursewares.length != 0) {
						this.chapters.list = resp.data.map(item => {
							// item.chapterName = item.chapterName
							item.index = this.$tools.uid(5)
							return item
						})
					}
					this.activeChapters(this.chapters.list[0] || {})
				} else {
					this.$msg({
						message: resp.msg,
						type: "error",
					})
				}
			})
		},
		//第二步保存
		async saveCourse() {
			if (
				this.chapters.list.some(item => {
					return !item.coursewares || item.coursewares.length == 0
				})
			) {
				this.$message.error("请为每个章节添加课件")
				return
			}
			this.chapters.list.map(e => {
				e.isRecommend = this.dataForm.isRecommend
				e.courseStatus = 2
				e.courseId = this.firstCourseId
			})
			await this.tableSubmitHandle(async () => {
				await this.handleStatus(2)
			})
		},
		saveCourseDraft() {
			this.chapters.list.map(e => {
				e.isRecommend = this.dataForm.isRecommend
				e.courseStatus = 2
				e.courseId = this.firstCourseId
			})
			this.tableSubmitHandle(async () => {
				await this.handleStatus(1)
			})
		},
		// 取消
		cancel() {
			this.$emit("refreshData")
			this.$refs["dataForm"] && this.$refs["dataForm"].resetFields()
			this.visible = false
		},
		// 表单提交 第二步
		tableSubmitHandle: debounce(function(cb) {
			this.saveloading = true
			saveStudyCourseChapter(this.chapters.list).then(async resp => {
				if (resp.code == 0) {
					this.$msg({
						type: "success",
						message: "操作成功!",
					})
					cb && (await cb())
					this.saveloading = false
					this.cancel()
					// this.$msg({
					// 	message: this.$t("prompt.success"),
					// 	type: "success",
					// 	duration: 500,
					// 	onClose: () => {
					// 		// this.visible = false
					// 		// this.$emit("refreshDataList")
					// 	},
					// })
				} else {
					this.saveloading = false
					this.$msg({
						message: resp.msg,
						type: "error",
					})
				}
			})
		}),
		// 表单提交 第一步
		dataFormSubmitHandle: debounce(
			function() {
				this.$refs["dataForm"].validate(valid => {
					if (valid) {
						this.step.active = 2
						this.saveloading = true
						//修改
						if (this.dataForm.id) {
							studycourseEdit(this.dataForm).then(resp => {
								if (resp.code == 0) {
									this.$message({
										type: "success",
										message: "操作成功!",
									})
									this.saveloading = false
									this.firstCourseId = resp.data
								} else {
									this.$msg({
										message: resp.msg,
										type: "error",
									})
								}
							})
							//新增
						} else {
							studycourseSave(this.dataForm).then(resp => {
								if (resp.code == 0) {
									this.$message({
										type: "success",
										message: "操作成功!",
									})
									this.saveloading = false
									this.firstCourseId = resp.data
									this.dataForm.id = resp.data
									this.getNextInfo()
								} else {
									this.$msg({
										message: resp.msg,
										type: "error",
									})
								}
							})
						}
					} else {
						return false
					}
				})
			},
			1000,
			{ leading: true, trailing: false },
		),
		async handleStatus(val) {
			let params = {
				id: this.firstCourseId,
				courseStatus: val,
			}
			await editCourseStatus(params)
		},
		//切换树数据选中状态
		handleSelectionChange(data) {
			this.selLeftTree.id = data.id
			this.selLeftTree.name = data.name
			this.dataForm.classifyId = data.id
		},
		//查询枚举数据
		queryEnumList() {
			this.CoursewareTypeList = []
			enumList("CoursewareType", "").then(resp => {
				if (resp.code == 0) {
					this.CoursewareTypeList = resp.data
				}
			})
		},
		//课程状态格式化返回
		coursewareTypeFmt(row) {
			let name = ""
			if (this.CoursewareTypeList) {
				this.CoursewareTypeList.forEach(item => {
					if (item.code == row.coursewareType) {
						name = item.name
					}
				})
			}
			return name
		},
	},
	components: {
		draggable,
		vSelectCourseware,
		pictureUpload,
	},
}
</script>

<style lang="scss" scoped>
.cpbcourse {
	padding: 20px;
}
ul,
li {
	list-style: none;
	margin: 0;
	padding: 0;
}
.left {
	border: 1px solid #eaeaea;
	position: relative;
	.header {
		border-bottom: 1px solid #eaeaea;
		line-height: 50px;
		height: 50px;
		padding-left: 20px;
		padding-right: 20px;
		em {
			float: right;
			font-style: normal;
			color: #bbb;
			font-size: 12px;
		}
	}
	.draggable {
		height: 320px;
		overflow-y: auto;
		li {
			padding: 0 20px;
			line-height: 20px;
			border-bottom: 1px solid #eaeaea;
			background: #fff;
			cursor: pointer;
			display: flex;
			justify-content: space-between;
			align-items: center;
			&.sortable-chosen {
				outline: 1px solid #eaeaea;
			}
			&.active {
				background: #f0f6ff;
				color: #1890ff;
			}
			.chapters-title-input {
				display: inline-block;
			}
			> div {
				flex: 1;
			}
			.btn {
				width: 50px;
				display: flex;
				flex: none;
				justify-content: space-around;
				align-items: center;
			}
		}
	}
	.footer {
		height: 60px;
		line-height: 60px;
		text-align: center;
		font-size: 15px;
		position: relative;
		cursor: pointer;
		&::before {
			content: "";
			position: absolute;
			top: 10px;
			bottom: 10px;
			right: 12px;
			left: 12px;
			border: 1px dashed #bbb;
		}
	}
}
.right {
	border: 1px solid #eaeaea;
	position: absolute;
	top: 0;
	bottom: 0;
	right: 0;
	.header {
		border-bottom: 1px solid #eaeaea;
		line-height: 50px;
		height: 50px;
		padding-left: 20px;
		padding-right: 20px;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	.table {
		height: calc(100% - 51px);
		overflow-y: auto;
		.thead,
		li {
			padding: 0px 20px;
			line-height: 50px;
			border-bottom: 1px solid #eaeaea;
			background: #fff;
			cursor: pointer;
			display: flex;
			justify-content: space-between;
			align-items: center;
		}
		.th {
			width: 100px;
			text-align: center;
		}
		.name {
			flex: 2;
			text-align: left;
			overflow: hidden;
			text-overflow: ellipsis;
			white-space: nowrap;
		}
		.number {
			text-align: left;
		}
	}
}
</style>
